package com.mszlu.blog.utils;

import com.alibaba.fastjson.JSON;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

@Component
public class QiniuUtils {

    //外链域名地址
    public static String qiniu_img_url_pre = "http://r8praeozx.hd-bkt.clouddn.com/";
    // 设置需要操作的账号的AK和SK
    public static final String ACCESS_KEY = "lfRNllOJhdKJ8XMrzQKXWM15TE5G13Y4ApCya1IF";
    private static final String SECRET_KEY = "jYUDEzqjjYsb1ZBK1qVqOhcr_El42f_k8I_cy7qr";
    // 要上传的空间名称
    private static final String BUCKETNAME = "haoh";

    public  boolean upload(MultipartFile file,String fileName){

        //构造一个带指定 Region 对象的配置类
        Configuration cfg = new Configuration(Zone.zone0());
        //...其他参数参考类注释
        UploadManager uploadManager = new UploadManager(cfg);
        String key = fileName;
        Auth auth = Auth.create(ACCESS_KEY,SECRET_KEY);
        String upToken =auth.uploadToken(BUCKETNAME);
        //默认不指定key的情况下，以文件内容的hash值作为文件名
        try {
            byte[] uploadBytes = file.getBytes();
            Response response = uploadManager.put(uploadBytes, fileName, upToken);
            //解析上传成功的结果
            DefaultPutRet putRet = JSON.parseObject(response.bodyString(), DefaultPutRet.class);
            return true;
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return false;
    }
}
